package CrowdCounting.RunnableTask;

import CrowdCounting.Model.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

public class PythonRunTask implements Runnable {

    private ArrayList<String> cmdList;
    private Process process;

    public PythonRunTask(String pythonInterpreter, String pythonScriptPath, boolean isBufferOut) {
        setCmdPara(pythonInterpreter, pythonScriptPath, isBufferOut);
    }

    public ArrayList<String> getCmdList() {
        return cmdList;
    }

    public void setCmdPara(String pythonInterpreter, String pythonScriptPath, boolean isBufferOut) {
        cmdList = new ArrayList<>();
        cmdList.add(pythonInterpreter);
        if (isBufferOut) cmdList.add("-u");
        cmdList.add(pythonScriptPath);
    }

    public void addInputValueToCmd(String value) {
        cmdList.add(value);
        System.out.println("命令行添加参数:" + value);
    }

    public Process getProcess(){
        return process;
    }
    @Override
    public void run() {
        if (cmdList.size() < 3 || cmdList.size() == 4) {
            Util.logger(Level.WARNING, "lack necessary parament for python script running");
            return;
        }
        if (cmdList.size() == 3) {
            Properties properties = Util.loadProperties("config.properties");
            cmdList.add(properties.getProperty("segmentSize"));
            cmdList.add(properties.getProperty("threshold"));
        }

        Util.logger(Level.INFO, cmdList.toString());
        process = runPythonScript(cmdList);
        checkErrorInfo();
    }

    public Process runPythonScript(String pythonInterpreterPath, String pythonScriptFilePath){
        try {
            String[] cmd = {pythonInterpreterPath,pythonScriptFilePath};
            Process process = Runtime.getRuntime().exec(cmd);
            return process;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Process runPythonScript(ArrayList<String> cmdList) {
        try {
            String[] cmd = cmdList.toArray(new String[0]);
            Process process = Runtime.getRuntime().exec(cmd);
            return process;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void endPythonScript(){
        try {
            while (isAlive() || !process.waitFor(1, TimeUnit.SECONDS)) {
                process.destroy();
            }
            System.out.println("python脚本退出码： " + process.exitValue());
            System.out.println("python程序中止");
        }catch (InterruptedException e1){
            throw new RuntimeException("python程序中止失败");
        }
    }

    public void checkErrorInfo() {
        try {
            BufferedReader isError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "gbk"));
            String lineErr;
            while ((lineErr = isError.readLine()) != null) {
                Util.logger(Level.WARNING, lineErr);
                System.out.println(lineErr);
            }
            isError.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getInfo(Process process) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
            String lineErr;
            while ((lineErr = in.readLine()) != null) {
                System.out.println(lineErr);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean isAlive(){
        if(process == null) return false;
        return process.isAlive();
    }
}
